const router = require('koa-router')()
const UsersController = require('../controller/users')
const HomeController = require('../controller/home')
const jwt = require('jsonwebtoken')

// sign
// verify


// token 登陆返回给前端的；
// 权限 => 0 1 

const auth = async (ctx, next) => {
  const { authorization } = ctx.request.headers;
  try {
    let data = jwt.verify(authorization, 'kkk')
    ctx.state.user = data;
    await next()
  } catch (e) {
    ctx.throw(401, '用户账号密码未授权')
    // ctx.body = {
    //   code: 401,
    //   msg: e.message
    // }
  }
}

router.prefix('/users')
// 登陆 注册
router.post('/login', HomeController.login)
// router.post('/register', HomeController.register)

// 业务
router.get('/search', UsersController.search)
router.get('/page', UsersController.page)

router.post('/', auth, UsersController.add)
router.delete('/:id', UsersController.delete)
router.put('/:id', UsersController.update)

module.exports = router
